#include <ClanLib/core.h>
#include <ClanLib/application.h>
#include <ClanLib/display.h>
#ifdef USE_SDL
	#include <ClanLib/sdl.h>
#else
	#include <ClanLib/gl.h>
#endif
#include <list>`
#include "viewport.h"
#include "parralax.h"

// Parralax
Parralax::Parralax()
{
}

Parralax::Parralax(const std::string &resource_id, CL_ResourceManager* manager)
{
  // Load resource
  CL_Resource resource = manager->get_resource(resource_id);
  resource.load();

  // Get data from resource
  ParralaxResourceData *data = 
    (ParralaxResourceData *) resource.get_data("parralax_data");

  // Throw error if data of wrong type
  if(!data)
    throw CL_Error("Resource '" + resource_id + "' is not of type 'parralax'");

  // Set variables
  xMultiplier = data->xMult;
  //std::cout << "Width: " << width << std::endl;
  yMultiplier = data->yMult;
  //std::cout << "Height: " << height << std::endl;
  surface = CL_Surface(data->surface,manager);

  // Unload resource
  resource.unload();
}

Parralax::~Parralax()
{
}

void Parralax::draw(Viewport &viewport)
{
  int width = surface.get_width();
  int height = surface.get_height();
  int left = viewport.get_world_area().left * -1;
  int top = viewport.get_world_area().top * -1;
  CL_Rect src(0, 0, width, height);
  CL_Rect dest(left * xMultiplier, top * yMultiplier,
	       left*xMultiplier + width, top*yMultiplier + height);
  viewport.draw(surface, src, dest); 
  //surface.draw(viewport.get_world_area().left *-1* xMultiplier,
  //       viewport.get_world_area().top *-1* yMultiplier,
  //       *viewport.get_window_gc());
}

// ParralaxManager
ParralaxManager::ParralaxManager()
{
}

ParralaxManager::~ParralaxManager()
{
}

void ParralaxManager::draw(Viewport &viewport)
{
	std::list<Parralax>::iterator it;

	for(it = parralax.begin() ; it != parralax.end() ; it++ )
	{
		it->draw(viewport);
	}
}

void ParralaxManager::add()
{
	Parralax parra;

	parralax.push_back(parra);
}

void ParralaxManager::add(Parralax &parra)
{
	parralax.push_back(parra);
}

void ParralaxManager::add(const std::string &resource_id, CL_ResourceManager* manager)
{
	Parralax parra(resource_id, manager);

	parralax.push_back(parra);
}

void ParralaxManager::clear()
{
	parralax.clear();
}

ParralaxResourceData::ParralaxResourceData(CL_Resource &resource) : CL_ResourceData(resource)
{
}

ParralaxResourceData::~ParralaxResourceData()
{
}

void ParralaxResourceData::on_load()
{
	CL_DomElement element = get_resource().get_element();
	xMult = CL_String::to_float(element.get_attribute("xMult"));
	yMult = CL_String::to_float(element.get_attribute("yMult"));
	surface = (std::string)element.get_attribute("surface");
}
